package com.ckx.blog.runner;

import com.ckx.constants.SystemConstants;
import com.ckx.domain.entity.Article;
import com.ckx.service.ArticleService;
import com.ckx.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 开机预存文章浏览数 Redis
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //获取 文章数据
        List<Article> articles = articleService.list();
        //将文章数据封装成 id - viewCount 的 map
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(
                        article -> article.getId().toString(), // key
                        article -> article.getViewCount().intValue())); // value
        //存入 Redis
        redisCache.setCacheMap(SystemConstants.ARTICLE_VIEWCOUNT, viewCountMap);

    }

}
